package com.ali.asyncgroup.context;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 自定义服务端处理器
 */
public class MyAsyncGroupContextServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 通道读取
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("接收消息：" + byteBuf.toString(StandardCharsets.UTF_8));
        System.out.println("线程名：" + Thread.currentThread().getName());

        //获取事件循环
        EventLoop eventLoop = ctx.channel().eventLoop();
        //异步普通任务
        eventLoop.execute(() -> {
            try {
                Thread.sleep(5000);
                System.out.println("异步普通任务");
                System.out.println("线程名：" + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //异步定时任务
        eventLoop.schedule(() -> {
            System.out.println("异步定时任务");
            System.out.println("线程名：" + Thread.currentThread().getName());
        }, 5, TimeUnit.SECONDS);
    }
}
